curRequests = [];

window.onload = function() {
    params = window.location.href.split("/");
    if (params.length > 0) {
        loadPage(params[4]);
    }
};

function loadPage(params) {
    switch (params) {
        case "home":
            break;
        case "explore":
            loadExplore();
            break;
        case "bret":
            $('.account-menu .item.active').removeClass('active');
            $('.account-menu .item.bret').addClass('active');
            loadBret();
            break;
        case "manager":
            $('.account-menu .item.active').removeClass('active');
            $('.account-menu .item.manager').addClass('active');
            loadBret();
            break;
    }
}

function loadExplore() {
    //get list most featured
    $.post('/bret/ws/brets', {
    }).done(function(data) {
        var r = JSON.parse(data);
        if (r !== null) {
            getMostFeaturedBrets_complete(r);
        }
    });
    //get most shared
    $.post('/bret/ws/mostshared', {
    }).done(function(data) {
        var r = JSON.parse(data);
        if (r !== null) {
            getMostSharedBrets_complete(r);
        }
    });
}

function loadBret() {
    $.post('/bret/ws/yourbrets', {
        'userid': currentUserId
    }).done(function(data) {
        var r = JSON.parse(data);
        if (r !== null) {
            getBrets_complete(r);
        }
    });
}

function getBrets_complete(r) {
    var brets = r;
    for (var i = 1; i < brets.length; i++) {
        var li = '<li class="bret-item"><a href=/bret/edit/' + brets[i].bretId + '>' +
                '<div class="preview">';
        if (brets[i].images === null || brets[i].images === undefined) {
            li += '<img src="Images/Preview_Bret.png"/>';
        } else {
            li += '<img src="' + brets[i].images[0].imageUrl + '"/>';
        }
        li += '</div><div class="details">' +
                '<p class="name">' + brets[i].name + '</p>' +
                '<p class="datecreated">' + brets[i].dateCreated + '</p>' +
                '<div class="bret-detail">' +
                '<div class="view">' +
                '<i class="fa fa-eye"></i><div>3000</div>' +
                '</div>' +
                '<div class="like">' +
                '<i class="fa fa-heart"></i><div>2000</div>' +
                '</div>' +
                ' </div>' +
                ' </div>' +
                '</a></li>';
        $('#bret-list').append(li);
    }
}

function getMostFeaturedBrets_complete(r) {
    var brets = r;
    if (brets.length > 0) {
        //the most feature
        var div = '<a href=/bret/edit/' + brets[0].bretId + '>';
        if (brets[0].images === null || brets[0].images === undefined) {
            div += '<div class="preview"><img src="Images/Preview_Bret.png"/></div>';
        } else {
            div += '<div class="preview"><img src="' + brets[0].images[0].imageUrl + '"/></div>';
        }
        div += '<div class="details">' +
                '<p class="name">' + brets[0].name + '</p>' +
                '<div><p class="datecreated">' + brets[0].dateCreated + '</p>' +
                '<div class="user">' +
                '<img src="Images/avatar.png"><span>' + $('#user-name').text() + '</span></div>' +
                '</div>' +
                '<div class="bret-detail">' +
                '<div class="view">' +
                '<i class="fa fa-eye"></i><div>3000</div>' +
                '</div>' +
                '<div class="like">' +
                '<i class="fa fa-heart"></i><div>2000</div>' +
                '</div>' +
                '<div class="retweet">' +
                '<i class="fa fa-retweet"></i><div>100</div>' +
                '</div>' +
                '</div>' +
                '</div></a>';
        $('#most-featured').html(div);
    }
    var length;
    if (brets.length > 7) {
        length = 7;
    } else {
        length = brets.length;
    }
    for (var i = 1; i < length; i++) {
        var li = '<li class="bret-item" data-id="' + brets[i].bretId + '"><a href=/bret/edit/' + brets[i].bretId + '>' +
                '<div class="preview">' +
                '<div class="cover-view">';
        if (brets[i].images === null || brets[i].images === undefined) {
            li += '<img src="Images/Preview_Mini.png"/>';
        } else {
            li += '<img src="' + brets[i].images[0].imageUrl + '"/>';
        }
        li += '<div class="part-preview">' +
                brets[i].description +
                '</div>' +
                '<div class="user">' +
                '<img src="Images/avatar.png"><span>' + brets[i].author["name"] + '</span>' +
                '</div>' +
                '<div class="bret-detail">' +
                '<div class="view">' +
                '<i class="fa fa-eye"></i><div>3000</div>' +
                '</div>' +
                '<div class="like">' +
                '<i class="fa fa-heart"></i><div>2000</div>' +
                '</div>' +
                '<div class="retweet">' +
                '<i class="fa fa-retweet"></i><div>100</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="details">' +
                '<p class="name">' + brets[i].name + '</p>' +
                '<p class="datecreated">' + brets[i].dateCreated + '</p>' +
                '</div>' +
                '</a></li>';
        $('#featured-list').append(li);
    }
}

function getMostSharedBrets_complete(r) {
    var brets = r;
    if (brets.length > 0) {
        //the most shared
        var div = '<a href=/bret/edit/' + brets[0].bretId + '>';
        if (brets[0].images === null || brets[0].images === undefined) {
            div += '<div class="preview"><img src="Images/Preview_Bret.png"/></div>';
        } else {
            div += '<div class="preview"><img src="' + brets[0].images[0].imageUrl + '"/></div>';
        }
        div += '<div class="details">' +
                '<p class="name">' + brets[0].name + '</p>' +
                '<div><p class="datecreated">' + brets[0].dateCreated + '</p>' +
                '<div class="user">' +
                '<img src="Images/avatar.png"><span>' + $('#user-name').text() + '</span></div>' +
                '</div>' +
                '<div class="bret-detail">' +
                '<div class="view">' +
                '<i class="fa fa-eye"></i><div>3000</div>' +
                '</div>' +
                '<div class="like">' +
                '<i class="fa fa-heart"></i><div>2000</div>' +
                '</div>' +
                '<div class="retweet">' +
                '<i class="fa fa-retweet"></i><div>100</div>' +
                '</div>' +
                '</div>' +
                '</div></a>';
        $('#most-shared').html(div);
    }
    var length;
    if (brets.length > 7) {
        length = 7;
    } else {
        length = brets.length;
    }
    for (var i = 1; i < length; i++) {
        var li = '<li class="bret-item" data-id="' + brets[i].id + '"><a href=/bret/edit/' + brets[i].bretId + '>' +
                '<div class="preview">' +
                '<div class="cover-view">';
        if (brets[i].images === null || brets[i].images === undefined) {
            li += '<img src="Images/Preview_Mini.png"/>';
        } else {
            li += '<img src="' + brets[i].images[0].imageUrl + '"/>';
        }
        li += '<div class="part-preview">' +
                brets[i].description +
                '</div>' +
                '<div class="user">' +
                '<img src="Images/avatar.png"><span>' + brets[i].name + '</span>' +
                '</div>' +
                '<div class="bret-detail">' +
                '<div class="view">' +
                '<i class="fa fa-eye"></i><div>3000</div>' +
                '</div>' +
                '<div class="like">' +
                '<i class="fa fa-heart"></i><div>2000</div>' +
                '</div>' +
                '<div class="retweet">' +
                '<i class="fa fa-retweet"></i><div>100</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="details">' +
                '<p class="name">' + brets[i].name + '</p>' +
                '<p class="datecreated">' + brets[i].dateCreated + '</p>' +
                '</div>' +
                '</a></li>';
        $('#shared-list').append(li);
    }
}

$(document).on('click', '.get-start', function() {
    window.location.href = '/bret';
});

function sendRequest(url, callback, process) {
    function getXMLHttpRequest() {
        if (window.XMLHttpRequest) {
            return new window.XMLHttpRequest;
        } else {
            try {
                return new ActiveXObject("MSXML2.XMLHTTP");
            } catch (ex) {
                return null;
            }
        }
    }
    var oReq = getXMLHttpRequest();
    function handler() {
        if (oReq.readyState === 4 /* complete */) {
            if (oReq.status === 200) {
                callback(oReq.responseText);
            }
        }
    }

    if (oReq !== null) {
        oReq.open("GET", url, true);
        oReq.onreadystatechange = handler;
        oReq.onprogress = progress;
        oReq.send();
        return oReq;
    } else {
        window.alert("AJAX (XMLHTTP) not supported.");
    }

    function progress() {
        process(oReq);
    }
}

function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

$(document).on('click', '.manager-list button', function() {
    //focus button clicked
    $('.manager-list button.selected').removeClass('selected');
    $(this).addClass('selected');
    //show table
    var type = $(this).attr('data-type').toLowerCase();
    switch (type) {
        case 'user':
        case 'bret':
            $('#profile').addClass('hide');
            $('.searchBox').removeClass('hide');
            $(".search-content").not('hide').addClass('hide');
            $("#" + type + "List").parent().parent().removeClass('hide');
            //reset search engine
            $('#doSearch').val('');
            $(".search-content:not(.hide) .dataTables_filter input").val('');
            $(".search-content:not(.hide) .dataTables_filter input").keyup();
            //reset choose
            $(".search-content:not(.hide) .dataTable input[name='checkAll']")[0].checked = false;
            var table_chbx = $(".search-content:not(.hide) .dataTable input[name^='check[']");
            for (var i = 0; i < table_chbx.length; i++) {
                table_chbx[i].checked = false;
            }
            break;
        case 'profile':
            $('#profile').removeClass('hide');
            $(".search-content").not('hide').addClass('hide');
            $('.searchBox').addClass('hide');
            break;
    }
});

$(document).on('click', ".dataTable input[name='checkAll']", function() {
    var checked = $(this)[0].checked;
    var table_chbx = $(this).parent().parent().parent().parent().find("input[name^='check[']");
    for (var i = 0; i < table_chbx.length; i++) {
        table_chbx[i].checked = checked;
    }
});

$(document).on('click', ".action-button .delete-btn", function() {
    var type = $(this).parent().attr('data-type');
    var checked_chbx = $(this).parent().parent().find("input[name^='check[']:checked");
    var ids = [];
    for (var i = 0; i < checked_chbx.length; i++) {
        ids.push(checked_chbx.eq(i).attr(type + 'id'));
    }
    $.ajax({
        url: "/bret/ws/delete" + type + "s",
        type: "POST",
        data: {ids: ids},
        success: function(r) {
            if (r === 'succeed') {
                switch (type.toUpperCase()) {
                    case 'USER':
                        var checked_chbx = $("#userList input[name^='check[']:checked");
                        for (var i = 0; i < checked_chbx.length; i++) {
                            checked_chbx.eq(i).parent().parent().remove();
                        }
                        break;
                    case 'BRET':
                        var checked_chbx = $("#bretList input[name^='check[']:checked");
                        for (var i = 0; i < checked_chbx.length; i++) {
                            checked_chbx.eq(i).parent().parent().find('.deleted').text('Yes');
                        }
                        break;
                }
            }
        }
    });
});

$(document).on('click', ".action-button .restore-btn", function() {
    var type = $(this).parent().attr('data-type');
    var checked_chbx = $(this).parent().parent().find("input[name^='check[']:checked");
    var ids = [];
    for (var i = 0; i < checked_chbx.length; i++) {
        ids.push(checked_chbx.eq(i).attr(type + 'id'));
    }
    $.ajax({
        url: "/bret/ws/restore" + type + "s",
        type: "POST",
        data: {ids: ids},
        success: function(r) {
            if (r === 'succeed') {
                var checked_chbx = $("#bretList input[name^='check[']:checked");
                for (var i = 0; i < checked_chbx.length; i++) {
                    checked_chbx.eq(i).parent().parent().find('.deleted').text('No');
                }
            }
        }
    });
});

$(document).on('click', ".action-button .enable-btn", function() {
    var type = $(this).parent().attr('data-type');
    var checked_chbx = $(this).parent().parent().find("input[name^='check[']:checked");
    var ids = [];
    for (var i = 0; i < checked_chbx.length; i++) {
        ids.push(checked_chbx.eq(i).attr(type + 'id'));
    }
    $.ajax({
        url: "/bret/ws/enable" + type + "s",
        type: "POST",
        data: {ids: ids},
        success: function(r) {
            if (r === 'succeed') {
                var checked_chbx = $("#userList input[name^='check[']:checked");
                for (var i = 0; i < checked_chbx.length; i++) {
                    checked_chbx.eq(i).parent().parent().find('.active').text('Yes');
                }
            }
        }
    });
});

$(document).on('click', ".action-button .disable-btn", function() {
    var type = $(this).parent().attr('data-type');
    var checked_chbx = $(this).parent().parent().find("input[name^='check[']:checked");
    var ids = [];
    for (var i = 0; i < checked_chbx.length; i++) {
        ids.push(checked_chbx.eq(i).attr(type + 'id'));
    }
    $.ajax({
        url: "/bret/ws/disable" + type + "s",
        type: "POST",
        data: {ids: ids},
        success: function(r) {
            if (r === 'succeed') {
                var checked_chbx = $("#userList input[name^='check[']:checked");
                for (var i = 0; i < checked_chbx.length; i++) {
                    checked_chbx.eq(i).parent().parent().find('.active').text('No');
                }
            }
        }
    });
});

$(document).on('click', ".action-button .add-btn", function() {
    var type = $(this).parent().attr('data-type');
    $.ajax({
        url: "/bret/ajax/new" + type,
        type: "POST",
        success: function(r) {
            if (type === 'user') {
                $('#modal').addClass('new-profile');
                $('#modal .modal-title').text('New Profile');
                $('#modal').attr('type', 'newProfile');
            }
            $('#modal .modal-body').html(r);
            $('#modal').modal('show');
        }
    });
});

function resetModal(id) {
    $('#' + id).attr('class', 'modal fade');
    setTimeout(function() {
        $('#' + id + ' .save-btn').removeClass('hide');
    }, 500);
}

$(document).on('click', '#modal button.close', function() {
    resetModal('modal');
});

$(document).on('click', '#modal button.close-btn', function() {
    resetModal('modal');
});

$(document).on('click', '#modal button.save-btn', function() {
    var type = $('#modal').attr('type');
    switch (type.toUpperCase()) {
        case 'NEWPROFILE':
            //validate
            var checkProfile = true;
            var error = '';
            var profile = {};
            var email = $('#c2022_email').val();
            var first_name = $('#c2022_first_name').val();
            var last_name = $('#c2022_last_name').val();
            var password = $('#c2022_password').val();
            var confirm_password = $('#c2022_confirm_password').val();
            var phone = $('#c2022_phone').val();
            if (validateEmail(email)) {
                profile.email = email;
            } else {
                checkProfile = false;
                error += '* Your email is invalid.';
            }
            if (first_name !== '' && last_name !== '') {
                profile.name = first_name + " " + last_name;
            } else {
                checkProfile = false;
                if (error !== '') {
                    error += "<br>* Your name can not empty.";
                } else {
                    error += "* Your name can not empty.";
                }
            }
            if (password !== '' && confirm_password !== '' && password === confirm_password) {
                profile.password = hex_md5(password);
            } else {
                checkProfile = false;
                if (error !== '') {
                    error += "<br>* Password is invalid.";
                } else {
                    error += "* Password is invalid.";
                }
            }
            var reg = new RegExp('^[0][1-9]{1}[0-9]{8,9}$');
            if (phone !== '' && reg.test(phone)) {
                profile.phone = phone;
            } else {
                checkProfile = false;
                if (error !== '') {
                    error += "<br>* Phone number is wrong.";
                } else {
                    error += "* Phone number is wrong.";
                }
            }
            profile.position = $('#c2022_position').val();
            profile.company = $('#c2022_company').val();
            profile.address = $('#c2022_address').val();
            if (checkProfile) {
                $.ajax({
                    url: "/bret/ws/addUser",
                    type: "POST",
                    data: {profile: JSON.stringify(profile)},
                    success: function(r) {
                        if(r !== 'duplicated') {
                            if (r !== 'false') {
                                var row = '<tr>' +
                                        '<td style="padding-left: 5px;">' +
                                            '<input type="checkbox" name="check[' + r + ']" userid="' + r + '"/></td>' +
                                        '<td>' + profile.email + '</td>' +
                                        '<td>' + profile.name + '</td>' +
                                        '<td>' + profile.company + '</td>' +
                                        '<td>' + profile.address + '</td>' +
                                        '<td>' + profile.phone + '</td>' +
                                        '<td data-time="' + moment().format('U') + '">' + moment().format('DD MMM YYYY HH:mm') + '</td>' +
                                        '<td class="active">No</td>' +
                                    '</tr>';
                                $('#userList tbody').append(row);
                            }
                        }else {
                            setTimeout(function() {
                                $('#modal .modal-title').text('Warning');
                                $('#modal .modal-body').html('The email is duplicated! Please choose another.');
                                $('#modal .save-btn').addClass('hide');
                                $('#modal').modal('show');
                            }, 700);
                        }
                    }
                });
                $('#modal button.close-btn').click();
            } else {
                //show error
                $('#modal .error').html(error);
            }
            break;
    }
});

$(document).on('click', '#change-password', function(data) {
    $('#change-password-form').animate({'height': 205, 'opacity': 1}, 500);
    $('.info-profile').animate({'height': 0, 'opacity': 0}, 500);
    $(this).attr('id', 'back-to-info');
    $(this).html('<i class="fa fa-back"></i>Back');
});
$(document).on('click', '#back-to-info', function(data) {
    $('#change-password-form').animate({'height': 0, 'opacity': 0}, 500);
    $('.info-profile').animate({'height': 244, 'opacity': 1}, 500);
    $(this).attr('id', 'change-password');
    $(this).html('<i class="fa fa-lock"></i>Change password');
});

$(document).on('click', '.user-profile .btn-red.commit', function(e) {
    $('.error').css('color', 'red');
    changeButton = $('.change-password a').last();
    if (changeButton.attr('id') !== 'change-password') {
        //change password
        oldPassword = $('#c2021_old_password').val();
        newPassword = $('#c2021_new_password').val();
        confirmPassword = $('#c2021_confirm_password').val();
        if (newPassword !== confirmPassword)
            $('.error').html("Error: Password does not match! Please check it!");
        else {
            tagName = $(this).prev().val();
            $.post("/bret/ws/changePassword", {oldpassword: hex_md5(oldPassword), newpassword: hex_md5(newPassword)}).done(function(r) {
                if (r === "succeed") {
                    window.location = '/bret/logout';
                }
                else {
                    $('.error').html("Error: " + r);
                }
            });
        }
    }
    else {
        //change info
        firstName = $('#c2021_first_name').val();
        lastName = $('#c2021_last_name').val();
        if (firstName !== '' && lastName !== '') {
            name = firstName + ' ' + lastName;
            var reg = new RegExp('^[0][1-9]{1}[0-9]{8,9}$');
            var phone = $('#c2021_phone').val();
            if (reg.test(phone)) {
                var company = $('#c2021_company').val();
                $.post("/bret/ws/updateProfile", {name: name, phone: phone, company: company, position: position}).done(function(r) {
                    if (r === "succeed") {
                        $('.error').css('color', 'green');
                        $('.error').html("Action performed successfully");
                    }
                    else {
                        $('.error').html("Something wrong :(");
                    }
                });
            } else {
                $('.error').html("Phone number is wrong...");
            }
            var formData = new FormData($('#upload-form')[0]);
            $.ajax({
                url: '/bret/ws/uploadavatar', //Server script to process data
                type: 'POST',
                xhr: function() {  // Custom XMLHttpRequest
                    var myXhr = $.ajaxSettings.xhr();
                    if (myXhr.upload) { // Check if upload property exists
                        myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },
                //Ajax events
                beforeSend: beforeSendHandler,
                success: completeHandler,
                error: errorHandler,
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        }
        else {
            $('.error').html("You cannot leave your name empty...");
        }
    }
});

$(document).on('keydown', '#c2021_phone', function(e) {
    // Allow: backspace, delete, tab, escape, enter
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
            // Allow: Ctrl+A
                    (e.keyCode === 65 && e.ctrlKey === true) ||
                    // Allow: home, end, left, right
                            (e.keyCode >= 35 && e.keyCode <= 39)) {
                // let it happen, don't do anything
                return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });
//validate uploading file
$(document).on('change', '#upload-zone', function() {
    var file = $(this)[0].files[0];
    var size = file.size;
    var type = file.type;
    //Your validation
    if (type !== 'image/gif' && type !== 'image/png' && type !== 'image/jpeg') {
        $(this).wrap('<form>').closest('form').get(0).reset();
        $(this).unwrap();
        $('.upload-error').html('Only accept png, gif or jpg');
    } else if (size > 500000) {
        $('.upload-error').html('Size of file must be lower 500kb.');
    } else {
        $('.upload-error').html();
        readURL(this);
    }
});
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#preview-avatar').attr('src', e.target.result);
        };
        reader.readAsDataURL(input.files[0]);
    }
}
function progressHandlingFunction(e) {
    /*if(e.lengthComputable){
     $('#upload-progress').attr({value:e.loaded,max:e.total});
     }*/
}
function beforeSendHandler(e) {
    console.log(e);
}
function completeHandler(e) {
    console.log(e);
}
function errorHandler(e) {
    console.log(e);
}

var timeHideMenu;
$(document).on('click', '.account', function() {
    $('.account-menu').addClass('show');
});
$(document).on('mouseover', '.account', function() {
    clearTimeout(timeHideMenu);
});
$(document).on('mouseover', '.account-menu', function() {
    clearTimeout(timeHideMenu);
});
$(document).on('mouseleave ', '.account', function() {
    timeHideMenu = setTimeout(function() {
        $('.account-menu').removeClass('show');
    }, 300);
});
$(document).on('mouseleave ', '.account-menu', function() {
    timeHideMenu = setTimeout(function() {
        $('.account-menu').removeClass('show');
    }, 300);
});
$(document).on('click', '.account-menu a', function() {
    $(this).parent().find('.active').removeClass('active');
    $(this).addClass('active');
});

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 